<template>
  <basic-container>
    <div class="header">
      <!--日期与模板-->
      <div class="header-up">
        <div class="date-template">
          <div class="dt-item">
            <el-date-picker
              size="mini"
              v-model="queryDate"
              type="daterange"
              align="right"
              unlink-panels
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              @change="() =>{
                this.page.current =1
                this.getData()}">
            </el-date-picker>
          </div>
          <div class="dt-item">
            <el-button size="mini" @click="tableColumnDrawer = true">自定义列</el-button>
          </div>
          <!--<div class="dt-item">-->
          <!--  <el-button size="mini" @click="kpiDrawer = true">kpi指标</el-button>-->
          <!--</div>-->

        </div>
      </div>
      <!--筛选条件-->
      <cs-filter-query ref="csFilterQueryRef" :options="filterQueryOptions"
                       @change="handleChangeFilter"></cs-filter-query>
    </div>

    <div class="data-report">
      <div class="curd-table">
        <div class="tab-header clearfix">
          <div class="tab-header-left">
          </div>
          <div class="tab-header-right">
            <el-tooltip class="item" effect="dark" content="清空" placement="top">
              <el-button icon="el-icon-delete" size="mini" circle @click="$refs.csFilterQueryRef.clear()"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="导出" placement="top">
              <el-button icon="el-icon-download" size="mini" circle @click="excelExport"></el-button>
            </el-tooltip>
          </div>
        </div>
        <div class="table-body">
          <el-table
            ref="table"
            v-loading="loading"
            :data="tableData"
            border
            show-summary
            :summary-method="summaryMethod"
            :header-cell-style="iHeaderCellStyle"
            @sort-change="sortTableData"
            style="width: 100%">
            <el-table-column
              type="index"
              width="50"
              label="#"
              :fixed="true">
            </el-table-column>
            <!--取消key值保证排序时重新渲染-->
            <el-table-column
              v-for="item in tableColumnData"
              :prop="item.value"
              :label="item.label"
              min-width="90"
              :sortable="item.sortable"
              :width="item.width?item.width:''"
              :fixed="item.fixed"
              :render-header="item.renderHeader">
              <template v-slot="{row}" v-if="item.value==='creativeUrl'">
                <div @click="handleMediaPreview(row)" style="display: inline-block"
                     :class="row.type == 1?'play-icon':''">
                  <video
                    v-if="row.type == 1"
                    style="width: 100px; height: 100px"
                    :src="row.creativeUrl"
                  >
                  </video>
                  <el-image
                    v-else
                    style="width: 100px; height: 100px"
                    :src="row.creativeUrl"
                    :fit="'cover'">
                  </el-image>
                </div>
              </template>
              <template v-slot="{row}" v-else-if="item.value==='designer'">
                {{ filterDesigner(row.designer) }}
              </template>
              <template v-slot="{row}" v-else-if="item.value==='operator'">
                {{ filterDesigner(row.operator) }}
              </template>

              <template v-slot="{row}" v-else-if="item.value==='country'">
                <el-tooltip effect="dark" :content="filterCountry(row.country)" placement="left">
                  <span class="over-flow">{{ filterCountry(row.country) }}</span>
                </el-tooltip>
              </template>
              <template v-slot="{row}" v-else-if="item.value==='ctr'">
                {{ row.ctr }}%
              </template>
              <template v-slot="{row}" v-else-if="item.value==='platform'">
                <div style="display: flex;flex-wrap: wrap;">
                  <div style="width: 20px;margin-right: 4px"
                       v-for="(item,index) in platformLogo(row.platform)"
                       :key="index">
                    <img style="width: 100%" :src="item.url" :title="item.name">
                  </div>
                </div>
              </template>
              <template v-slot="{row}" v-else-if="item.value==='cvr'">
                {{ row.cvr }}%
              </template>
              <template v-slot="{row}" v-else-if="item.value==='os'">
                {{ row.os | filterOs }}
              </template>
              <template v-slot="{row}" v-else-if="item.value==='installCost'">
                {{ row.installCost | thousandSeparator }}
              </template>
              <template v-slot="{row}" v-else-if="item.value==='performanceName'">
                <el-tooltip effect="dark" :content="row.performanceName" placement="left">
                  <span class="over-flow">{{ row.performanceName }}</span>
                </el-tooltip>
              </template>
              <template v-slot="{row}" v-else-if="item.value==='localFilename'">
                <el-tooltip effect="dark" :content="row.localFilename" placement="left">
                  <span class="over-flow">{{ row.localFilename }}</span>
                </el-tooltip>
              </template>
              <template v-slot="{row}" v-else-if="item.value==='allExpend'">
                {{ row.allExpend | thousandSeparator }}
              </template>
              <template v-slot="{row}" v-else-if="item.value==='impressions'">
                {{ row.impressions | thousandSeparator }}
              </template>
              <template v-slot="{row}" v-else-if="item.value==='clicks'">
                {{ row.clicks | thousandSeparator }}
              </template>
              <template v-slot="{row}" v-else-if="item.value==='install'">
                {{ row.install | thousandSeparator }}
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              width="50">
              <template v-slot="{row}">
                <el-tooltip content="查看" placement="top">
                  <el-button size="small" icon="el-icon-view" type="text" @click="checkRow(row)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="bottom-page clearfix">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page.current"
            :page-sizes="[10, 20, 30, 40, 50, 100]"
            :page-size="page.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </div>
      <el-drawer
        title="自定义列"
        size="800px"
        :visible.sync="tableColumnDrawer"
        :modal-append-to-body="false"
        :close-on-click-modal="false"
        :append-to-body="true"
        :wrapperClosable="false"
      >
        <el-divider></el-divider>
        <cs-drawer-container>
          <div class="drawer-box">
            <div class="drawer-box-left">
              <div class="drawer-box-left-input">
                <el-input v-model="headerQueryIntputLeft" size="mini" prefix-icon="el-icon-search"
                          placeholder="请输入搜索内容" clearable></el-input>
              </div>
              <div class="drawer-box-left-tab">
                <el-tabs type="border-card">
                  <el-tab-pane label="维度">
                    <el-checkbox-group v-model="checkedDimCol">
                      <el-checkbox v-for="item in dimSearchData" :label="item.value" :key="item.value"
                                   :disabled="item.disabled"
                                   @change="handleCheckedDimCol($event,item)">{{ item.label }}
                      </el-checkbox>
                    </el-checkbox-group>
                  </el-tab-pane>
                  <el-tab-pane label="基础指标">
                    <el-checkbox-group v-model="checkedBaseTarget">
                      <el-checkbox v-for="item in targetSearchData" :label="item.value" :key="item.value"
                                   :disabled="item.disabled"
                                   @change="handleCheckedDimCol($event,item)">{{ item.label }}
                      </el-checkbox>
                    </el-checkbox-group>
                  </el-tab-pane>
                </el-tabs>
              </div>
            </div>
            <div class="drawer-box-right">
              <el-input v-model="headerQueryIntputRight" size="mini" prefix-icon="el-icon-search"
                        placeholder="请输入搜索内容" clearable></el-input>
              <div class="select-label">已选{{ tableHeaderOpt.length }}列</div>
              <draggable v-model="tableHeaderOpt" chosenClass="chosen" forceFallback="true" group="people"
                         filter=".forbid"
                         animation="100"
                         :move="onMove">
                <transition-group>
                  <div :class="isDisabled(item.value)?'drag-box forbid':'drag-box'"
                       v-for="item in rightSearchData" :key="item.value">
                    <div class="drag-box-left">
                      <i class="myicon icon-igw-l-menu-2"></i>
                      <span>{{ item.label }}</span>
                    </div>
                    <div class="drag-box-right" v-show="!isDisabled(item.value)">
                      <i class="myicon icon-zhiding" @click="upCheckedCol(item)"></i>
                      <i class="myicon icon-cha" @click="removeCheckedCol(item)"></i>
                    </div>
                  </div>
                </transition-group>
              </draggable>
            </div>
          </div>
          <el-button slot="bottom" size="mini" type="primary" @click="createReport">生成报告</el-button>
        </cs-drawer-container>
      </el-drawer>
    </div>
    <creative-performance-detail width="80%" ref="creativePerformanceDetail"></creative-performance-detail>
    <!--预览弹窗-->
    <creative-card-preview v-model="mediaPreviewDialog.dialogVisible"
                           :media-preview="currentCreative"></creative-card-preview>
    <!--    <kpi-config :visible.sync="kpiDrawer"></kpi-config>-->
  </basic-container>
</template>

<script>
import CsFilterQuery from "@/components/CsFilterQuery/CsFilterQuery";
import CsDrawerContainer from "@/components/CsDrawerContainer/CsDrawerContainer";
import {
  getOffer,
} from "@/api/dataReport/cost-report-new";
import Moment from "moment";
import {getSysDictList} from "@/api/system/dict";
import draggable from "vuedraggable"
import {exportExcel2, getCreativeReportList, getKpiConfig, submitKpiConfig} from "@/api/offer/creativeperformance";
import {getAllUser} from "@/api/user";
import _ from 'lodash'
import creativePerformanceDetail from '@/views/creativeReport/components/creativeperformancedetailBc'
import CreativeCardPreview from "@/components/CreativeCardPreview/CreativeCardPreview";
import KpiConfig from "@/views/creativeReport/components/KpiConfig";
import {columnTip} from "@/util/util";
import {platformLogo} from "../../util/beetles";

export default {
  name: "CreativePerformanceNew",
  components: {
    CsFilterQuery,
    CsDrawerContainer,
    creativePerformanceDetail,
    draggable,
    CreativeCardPreview,
    // KpiConfig

  },
  data() {
    const end = new Date();
    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
    const that = this
    return {
      key: 0,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },
      // 查询日期范围
      queryDate: [Moment(start).format('YYYY-MM-DD'), Moment(end).format('YYYY-MM-DD')],
      // 模板
      currentTemplate: '0',
      loading: false,
      // 表格数据
      tableData: [],
      page: {
        current: 1,
        size: 10,
      },
      total: 0,
      // 显隐弹窗
      tableColumnDrawer: false,
      // 显隐配置项
      tableColumnData: [],
      // 过滤参数
      filterQueryInfo: {},
      // 表格头部配置
      tableHeaderOpt: [],
      // 花费统计
      costTotal: '',
      // 订单
      offerList: [],
      // 固定表头
      fixed: ["offerName", "platformId", "customerName", "platform", "operatorName", "salesManagerName", "customerManagerName", "totalCost", "monthSum", "monthExpectedSum", "lastMonthSum"],
      // 左对齐的表头
      alignLeftHeader: ["offerName", "platformId", "customerName", "platform", "operatorName", "salesManagerName", "customerManagerName"],
      // 设计师
      userList: [],
      // 媒体
      platformList: [],
      // 地区
      nationList: [],
      // 自定义列搜索
      headerQueryIntputLeft: '',
      headerQueryIntputRight: '',
      // kpi抽屉
      kpiDrawer: false,
      kpiForm: {
        target: '',
        filterItems: [{
          platform: '',
          os: '',
          country: '',
          standard: {},
          exceed: {}
        }]
      },
      oslist: [
        {
          label: 'Android',
          value: '1'
        }, {
          label: 'IOS',
          value: '2'
        }, {
          label: 'Website',
          value: '3'
        }
      ],
      // 维度参数
      dimColList: [
        {
          label: '素材',
          value: "creativeUrl",
          disabled: true,
          checked: true,
          fixed: true
        }, {
          label: '素材ID',
          value: "shortId",
          disabled: true,
          checked: true,
          fixed: true
        }, {
          label: '素材名称',
          value: "performanceName",
          checked: true
        }, {
          label: '本地文件名',
          value: "localFilename",
          checked: true
        }, {
          label: '订单名',
          value: "offerName",
          checked: true
        }, {
          label: '设计师',
          value: "designer",
          checked: true
        }, {
          label: '优化师',
          value: 'operator',
        }, {
          label: '投放地区',
          value: "country",
          checked: true,
          renderHeader: (h, {column}) => {
            return columnTip(h, column, '广告/素材实际产生归因数据的国家/地区')
          }
        }, {
          label: '投放媒体',
          value: "platform",
          checked: true,
          renderHeader: (h, {column}) => {
            return columnTip(h, column, '广告/素材实际产生归因数据的平台')
          }
        }, {
          label: '需求ID',
          value: 'requestId',
        }, {
          label: '需求名称',
          value: 'requestName',
        }, {
          label: '操作系统',
          value: 'os',
        }
      ],
      checkedDimCol: [],
      defaultTableOpt: [],
      // 基础指标
      baseTargetList: [
        {
          label: '花费',
          value: "allExpend",
          sortable: 'custom',
          checked: true
        }, {
          label: '曝光',
          value: "impressions",
          sortable: 'custom',
          checked: true
        }, {
          label: '点击',
          value: "clicks",
          sortable: 'custom',
          checked: true
        }, {
          label: 'CTR',
          value: "ctr",
          sortable: 'custom',
          checked: true
        }, {
          label: '安装',
          value: "install",
          sortable: 'custom',
          checked: true
        }, {
          label: 'CVR',
          value: "cvr",
          sortable: 'custom',
          checked: true
        }, {
          label: '安装成本',
          value: 'installCost',
          sortable: 'custom',
          checked: true
        }
      ],
      checkedBaseTarget: [],
      // 排序
      sortList: [],

      currentCreative: null,

      mediaPreviewDialog: {
        dialogVisible: false,
        // dialogType: "image", //image or video
        // previewUrl: "",
      },
    }
  },
  filters: {
    filterOs(origin) {
      const oslist = [
        {
          label: 'Android',
          value: '1'
        }, {
          label: 'IOS',
          value: '2'
        }, {
          label: 'Website',
          value: '3'
        }
      ]
      try {
        const osArr =_.compact(origin.split(','))
        const nameArr = osArr.map(item => {
          return oslist.find(item1 => item1.value == item).label
        })
        return nameArr.join(',')
      } catch (e) {
        return ''
      }

    }
  },
  computed: {
    // 筛选组件配置
    filterQueryOptions() {
      return [
        {
          value: 'shortId',
          label: '短ID',
        },
        {
          value: 'name',
          label: '素材名',
        },
        {
          value: 'localFilename',
          label: '本地文件名',
        },
        {
          value: 'type',
          label: '素材类型',
          children: [
            {
              value: '0',
              label: '图片',
            },
            {
              value: '1',
              label: '视频',
            }
          ]
        }, {
          value: 'offerName',
          label: '订单名称',
          queryList: this.offerList
        }, {
          value: 'designer',
          label: '设计师',
          queryList: this.userList
        }, {
          value: 'operator',
          label: '优化师',
          queryList: this.userList
        }, {
          value: 'platform',
          label: '投放媒体',
          children: this.platformList
        }, {
          value: 'country',
          label: '投放地区',
          queryList: this.nationList
        },
        {
          value: 'os',
          label: '操作系统',
          children: [
            {
              label: 'Android',
              value: '1'
            }, {
              label: 'IOS',
              value: '2'
            }, {
              label: 'Website',
              value: '3'
            }
          ]
        },
        {
          value: 'requestId',
          label: '需求ID'
        }, {
          value: 'requestName',
          label: '需求名称'
        }]
    },
    // 右边搜索栏
    rightSearchData() {
      if (this.headerQueryIntputRight) {
        return this.tableHeaderOpt.filter(item => {
          const input = this.headerQueryIntputRight.toLowerCase()
          const label = item.label.toLowerCase()
          return label.includes(input)
        })
      } else {
        return this.tableHeaderOpt
      }
    },
    // 维度搜索
    dimSearchData() {
      if (this.headerQueryIntputLeft) {
        return this.dimColList.filter(item => {
          const input = this.headerQueryIntputLeft.toLowerCase()
          const label = item.label.toLowerCase()
          return label.includes(input)
        })
      } else {
        return this.dimColList
      }
    },
    // 基础指标搜索
    targetSearchData() {
      if (this.headerQueryIntputLeft) {
        return this.baseTargetList.filter(item => {
          const input = this.headerQueryIntputLeft.toLowerCase()
          const label = item.label.toLowerCase()
          return label.includes(input)
        })
      } else {
        return this.baseTargetList
      }
    },
  },
  created() {
    this.initHeaderCol()
    this.getData()
    getAllUser().then((res) => {
      this.userList = res.data.data.map(item => {
        return {
          label: item.realName,
          value: item.id
        }
      })
    })

    getSysDictList("platforms,nation").then((map) => {
      this.platformList = map['platforms'].map(item => {
        return {
          label: item.dictValue,
          value: item.dictKey
        }
      })
      this.nationList = map['nation'].map(item => {
        return {
          label: item.dictKey,
          value: item.dictKey
        }
      })
    })
    this.getOfferList()
  },
  mounted() {
  },
  methods: {
    //弹出预览框
    handleMediaPreview(row) {
      this.currentCreative = row
      // this.mediaPreviewDialog.previewUrl = row.creativeUrl + "?" + (row.updateTime ? row.updateTime.replace(/[ :-]*/gi, "") : 1234);
      // this.mediaPreviewDialog.dialogType = row.type == 0 ? "image" : "video";
      this.mediaPreviewDialog.dialogVisible = true;
    },
    iHeaderCellStyle() {
      return {
        color: '#101010',
        backgroundColor: '#F2F2F2'
      }
    },
    handleSizeChange(val) {
      // console.log(this.$refs.csFilterQueryRef)
      this.$refs.csFilterQueryRef.$el.scrollIntoView()
      this.page.size = val
      this.getData()
    },
    handleCurrentChange(val) {
      // console.log(this.$refs.csFilterQueryRef.$el)
      this.$refs.csFilterQueryRef.$el.scrollIntoView()
      this.page.current = val
      this.getData()
    },
    // 获取数据
    async getData() {
      const params = {
        ...this.page,
        sortList: JSON.stringify(this.sortList)
      }
      const data = {
        beginDate: this.queryDate ? this.queryDate[0] : null,
        endDate: this.queryDate ? this.queryDate[1] : null,
        ...this.filterQueryInfo,
      }
      this.loading = true
      const {data: res} = await getCreativeReportList(
        params, data).finally(() => {
        this.loading = false
      })
      this.tableData = res.data.records
      this.total = res.data.total
    },
    // 筛选框查询
    handleChangeFilter(val) {
      this.filterQueryInfo = val
      this.page.current = 1
      this.getData()
    },
    // 侧边生成报告
    createReport() {
      this.loading = true
      this.tableColumnData = _.cloneDeep(this.tableHeaderOpt)
      this.tableColumnDrawer = false
      this.page.current = 1
      this.getData()
      this.loading = false
    },
    //取消生成
    cancelCreate() {
      this.getData()
    },
    // 导出报告
    async excelExport() {
      const res = await exportExcel2({
        ...this.page,
        beginDate: this.queryDate[0],
        endDate: this.queryDate[1],
        sortList: JSON.stringify(this.sortList),
        ...this.filterQueryInfo,
      })
      let filename = window.decodeURI(res.headers['content-disposition'].split('=')[1])
      let url = window.URL.createObjectURL(new Blob([res.data]))
      let link = document.createElement("a")
      link.style.display = "none"
      link.href = url
      link.download = filename
      document.body.appendChild(link)
      link.click()
    },
    // 获取订单
    async getOfferList() {
      const {data: res} = await getOffer()
      this.offerList = res.data.map(item => {
        return {
          value: item.key,
          label: item.name
        }
      })
    },
    // 维度选择框事件
    handleCheckedDimCol(event, val) {
      if (event) {
        // 添加对象
        this.tableHeaderOpt.push(val)
      } else {
        // 删除对象
        this.tableHeaderOpt = _.remove(this.tableHeaderOpt, function (n) {
          // 数组中的对象
          return !_.isEqual(n, val) // 比较对象
        })
      }
    },
    // 移除已选择列
    removeCheckedCol(val) {
      this.tableHeaderOpt = _.remove(this.tableHeaderOpt, function (n) {
        // 数组中的对象
        return !_.isEqual(n, val) // 比较对象
      })
      this.checkedDimCol = _.remove(this.checkedDimCol, function (n) {
        // 数组中的对象
        return n !== val.value
      })
      this.checkedBaseTarget = _.remove(this.checkedBaseTarget, function (n) {
        // 数组中的对象
        return n !== val.value
      })
    },
    // 置顶已选择列
    upCheckedCol(val) {
      const dis = this.dimColList.filter(item => item.disabled)
      this.tableHeaderOpt = _.remove(this.tableHeaderOpt, function (n) {
        // 数组中的对象
        return !_.isEqual(n, val) // 比较对象
      })
      this.tableHeaderOpt.splice(dis.length, 0, val)
      // this.tableHeaderOpt.unshift(val)
    },
    //禁止拖动到id为1的对象
    onMove(e) {
      // console.log(e.relatedContext.element.value)
      const dis = this.dimColList.filter(item => item.disabled).map(item => item.value)
      if (dis.includes(e.relatedContext.element.value)) return false;
      return true;
    },
    // 禁用的行
    isDisabled(value) {
      if (value === 'creativeUrl' || value === 'shortId') {
        return true
      } else {
        return false
      }
    },
    // 初始化表头
    initHeaderCol() {
      this.tableHeaderOpt = [...this.dimColList.filter(item => item.checked), ...this.baseTargetList.filter(item => item.checked)]
      this.checkedDimCol = this.dimColList.filter(item => item.checked).map(item => item.value)
      this.checkedBaseTarget = this.baseTargetList.filter(item => item.checked).map(item => item.value)
      this.tableColumnData = [...this.tableHeaderOpt]
    },
    dialogType(val) {
      let type;
      let urlTail = val.split(".")[val.split(".").length - 1];
      let imgList = ["jpg", "jpeg", "png", "gif", "bmp"];
      let videoList = ["mp4", "mov", "avi", "mp3", "ogg", "rmvb", "mkv"];
      if (imgList.includes(urlTail)) {
        type = "image";
      } else if (videoList.includes(urlTail)) {
        type = "video";
      }
      return type;
    },
    summaryMethod({columns, data}) {
      const ign = ["creativeUrl", "shortId", "performanceName", "localFilename", "offerName", "designer", "platform", "country"]
      const sums = [];
      let allExpendSum = 0;
      let impressionsSum = 0;
      let clicksSum = 0;
      let ctrSum = 0;
      let installSum = 0;
      let cvrSum = 0;
      let installCostSum = 0;
      if (data.length > 0) {
        data.forEach((row) => {
          allExpendSum += parseFloat(row.allExpend)
          impressionsSum += parseFloat(row.impressions)
          clicksSum += parseFloat(row.clicks)
          ctrSum += parseFloat(row.ctr)
          installSum += parseFloat(row.install)
          cvrSum += parseFloat(row.cvr)
          installCostSum += parseFloat(row.installCost)
        })
      }
      if (columns.length > 0) {
        columns.forEach((column, index) => {
          if ([0].includes(index)) {
            sums[index] = '合计'
          } else if (column.label && column.label === "花费") {
            sums[index] = this.thousandSeparator(allExpendSum.toFixed(2))
          } else if (column.label && column.label === "曝光") {
            sums[index] = impressionsSum = this.thousandSeparator(impressionsSum.toFixed(2))
          } else if (column.label && column.label === "点击") {
            sums[index] = clicksSum = this.thousandSeparator(clicksSum.toFixed(2))
          } else if (column.label && column.label === "CTR") {
            sums[index] = ctrSum = this.thousandSeparator(ctrSum.toFixed(2)) + "%"
          } else if (column.label && column.label === "安装") {
            sums[index] = installSum = this.thousandSeparator(installSum.toFixed(2))
          } else if (column.label && column.label === "CVR") {
            sums[index] = cvrSum = this.thousandSeparator(cvrSum.toFixed(2)) + "%"
          } else if (column.label && column.label === "安装成本") {
            sums[index] = installCostSum = this.thousandSeparator(installCostSum.toFixed(2))
          } else {
            // marco
            // sums[index] = this.tableColumnValue.map(item => Number(item[column.property]));
            sums[index] = ''
          }
        });
      }
      return sums;
    },
    thousandSeparator(num) {
      let s = num.toString();
      let div = s.indexOf('.');
      let sign = (num < 0) ? '-' : '';
      let intPart = (div == -1) ? s : s.substring(0, div);
      let dotPart = (div == -1) ? '' : s.substring(div);
      let finalIntPart = '';
      while (intPart.length > 3) {
        finalIntPart = ',' + intPart.substring(intPart.length - 3) + finalIntPart;
        intPart = intPart.substring(0, intPart.length - 3);
      }
      return sign + intPart + finalIntPart + dotPart;
    },
    // 添加指标
    addFilterItems() {
      this.kpiForm.filterItems.push(
        {
          platform: '',
          os: '',
          country: '',
          standard: {},
          exceed: {}
        }
      )
    },
    // 移除指标
    removeFilterItems(index) {
      this.kpiForm.filterItems.splice(index, 1)
    },
    // 提交kpi指标
    async submitKpiTarget() {
      this.kpiDrawer = false
      const {data: res} = await submitKpiConfig(this.kpiForm)
      if (res.code !== 200) return
      this.onLoad()
    },
    // 获取kpi数据
    async getKpiConfig() {
      const {data: res} = await getKpiConfig()
      if (res.data.id === undefined) return
      this.kpiForm.id = res.data.id
      this.kpiForm.target = res.data.target
      this.kpiForm.filterItems = res.data.filterItems
    },
    // 设计师显示
    filterDesigner(designer) {
      let designers = designer.split(",");
      let designerList = this.userList;
      let name = [];
      for (let i in designerList) {
        let designerId = designerList[i].value;
        let designerName = designerList[i].label;
        for (let j in designers) {
          let designer = designers[j];
          if (designer === designerId) {
            name.push(designerName);
          }
        }
      }
      return name.join(",");
    },
    // 投放国家转换
    filterCountry(val) {
      if (val === '') return ''
      const arr = val.split(',')
      return arr.map(value => this.nationList.find(item => item.value === value)).map(
        item => {
          if (item !== undefined) {
            return item.label
          } else
            return '未知'
        }
      ).join(', ')
    },
    // 排序
    sortTableData(val) {
      let prop = val.prop;
      let orderBy = null;
      if (val.order === "descending") {
        orderBy = 'desc';
        //向上排序
      } else if (val.order === "ascending") {
        orderBy = 'asc';
        //不排序
      }
      if (orderBy != null) {
        this.sortList = [{name: prop, orderBy: orderBy}];
      } else {
        this.sortList = [];
      }
      this.getData()
    },
    checkRow(row) {
      this.$refs.creativePerformanceDetail.queryForm = {
        platform: null,
        beginDate: null,
        endDate: null,
        nationList: [],
        updateDateRange: this.queryDate,
      }
      this.$refs.creativePerformanceDetail.showDialog({
        creativeId: row.creativeId,
        shortId: row.shortId,
        performanceName: row.performanceName
      });
    },
    // 切换默认模板
    changeDefualtTemplate() {
      this.tableHeaderOpt = this.dimColList.filter(item => item.checked)
      this.checkedDimCol = this.tableHeaderOpt.map(item => item.value)
      this.tableColumnData = [...this.tableHeaderOpt]
      this.templateSelect = ''
      this.checkedBaseTarget = []
      this.onLoad()
    },
    platformLogo(platform) {
      return platformLogo(platform)
    },
  }
}
</script>

<style lang="scss" scoped>
* {
  box-sizing: border-box;
}

.header {

  .header-up {
    display: flex;
    justify-content: space-between;

    .date-template {
      .dt-item {
        display: inline-block;
        margin-bottom: 10px;
        margin-right: 10px;
      }
    }

  }

}

.card-header {
  display: flex;
  justify-content: flex-end;
}

::v-deep .el-card__header {
  border-bottom: unset;
}

.curd-table {
  .tab-header {
    font-size: 14px;
    margin-bottom: 15px;

    .tab-header-left {
      float: left;

      & > * {
        margin-right: 15px;
      }
    }

    .tab-header-right {
      float: right;
    }
  }

  .bottom-page {
    height: 100px;
    margin-top: 15px;

    .el-pagination {
      float: right;
    }
  }

  .over-flow {
    overflow: hidden; //溢出内容隐藏
    text-overflow: ellipsis; //文本溢出部分用省略号表示
    white-space: nowrap;
  }

  ::v-deep .cell {
    //overflow: hidden; //溢出内容隐藏
    //text-overflow: ellipsis; //文本溢出部分用省略号表示
    //display: -webkit-box; //特别显示模式
    //-webkit-line-clamp: 2; //行数
    //line-clamp: 2;
    //-webkit-box-orient: vertical; //盒子中内容竖直排列
  }
}

.el-transfer {
  height: 100%;
  display: -webkit-box;

  /deep/ .el-transfer-panel {
    height: 100%;

    .el-transfer-panel__body {
      height: 100%;

      .el-transfer-panel__list {
        height: 100%;
      }
    }
  }
}

.clearfix:after {
  content: "";
  display: block;
  clear: both;
}

.el-checkbox-group {
  display: flex;
  flex-direction: column;
}

.drawer-box {
  padding: 0 15px;
  display: flex;
  justify-content: space-between;
  height: 100%;

  .el-input {
    ::v-deep .el-input__inner {
      border-radius: 15px;
    }
  }

  .drawer-box-left {
    border: 1px solid #E8E8E8;
    border-radius: 5px;
    flex: 1;
    margin-right: 15px;
    display: flex;
    flex-direction: column;

    .drawer-box-left-input {
      padding: 15px 20px;
    }

    .drawer-box-left-tab {
      flex: 1;

      .el-tabs {
        height: 100%;
        box-sizing: border-box;
        box-shadow: unset;
        border-bottom: unset;
        border-left: unset;
        border-right: unset;

        .el-checkbox-group {
          display: block;

          .el-checkbox {
            width: 25%;
          }
        }
      }
    }
  }

  //.drawer-box-right {
  //  width: 300px;
  //  border: 1px solid #E8E8E8;
  //  border-radius: 5px;
  //  padding: 15px 20px;
  //
  //  .select-label {
  //    line-height: 45px;
  //    height: 45px;
  //    font-size: 14px;
  //  }
  //}
  .drawer-box-right {
    width: 300px;
    border: 1px solid #E8E8E8;
    border-radius: 5px;
    padding: 15px 20px;
    display: flex;
    flex-direction: column;

    .select-label {
      line-height: 45px;
      height: 45px;
      font-size: 14px;
    }

    .tableHeaderOpt {
      flex: 1;
      overflow: auto;
    }
  }

  .drag-box {
    padding: 5px 0;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    cursor: move;

    .drag-box-left {
      color: #101010;
      font-size: 14px;

      i {
        margin-right: 18px;
      }
    }

    .drag-box-right {
      i {
        cursor: pointer;

        &:first-child {
          margin-right: 18px;
        }
      }
    }
  }
}

.forbid {
  cursor: default !important;
}

.kpi-box {
  padding: 0 15px;

  .el-table {
    ::v-deep .cell {
      display: flex;
    }
  }
}

.play-icon {
  display: inline-block;
  position: relative;

  &::before {
    content: '\ec61';
    font-family: 'myicon';
    font-size: 30px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: #FFFFFF;
  }
}
</style>
